package com.flashcash.solu.view.login;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import com.flashcash.solu.BuildConfig;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.BaseActivity;
import com.flashcash.solu.bean.LoginRequestBean;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.common.network.CaptchaApi;
import com.flashcash.solu.view.login.presenter.LoginActPresenter;
import com.flashcash.solu.view.login.presenter.LoginactPreImpl;
import com.flashcash.solu.widget.selfdefdialog.DialogManager;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants;
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils;
import com.flashcash.kotlin.utils.SpanBuilder;
import com.flashcash.kotlin.widget.LocalButton;
import com.flashcash.kotlin.widget.LocalEditText;
import com.flashcash.kotlin.widget.LocalImageButton;
import com.flashcash.kotlin.widget.LocalImageView;
import com.flashcash.kotlin.widget.LocalTextView;
import com.x.leo.apphelper.log.XLog;


import org.apache.commons.lang3.RandomStringUtils;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tongdun.android.shell.FMAgent;
import cn.tongdun.android.shell.exception.FMException;

import java.util.HashMap;
import java.util.Map;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;


/**
 * Created by Miaoke on 2017/2/28.
 */

public class LoginActivity extends BaseActivity<LoginActPresenter> implements LoginActView {


    @BindView(R.id.id_button_login)
    LocalButton login;
    @BindView(R.id.id_edittext_phone_number)
    LocalEditText editTextPhone;
    @BindView(R.id.id_edittext_SMS_code)
    LocalEditText editTextSMSCode;
    @BindView(R.id.id_login_statement)
    LocalTextView mStatementNotify;
    @BindView(R.id.id_imageview_code)
    LocalImageView imageViewCode;
    @BindView(R.id.id_imagebutton_refresh)
    LocalImageButton imButtonRefresh;
    @BindView(R.id.id_button_obtain_code)
    LocalButton buttonObtain;
    @BindView(R.id.id_edittext_graphical_code)
    LocalEditText editTextGraphicalCode;
    @BindView(R.id.id_linearlayout_graphical_code)
    LinearLayout linearLayoutGraphical;
    @BindView(R.id.id_edittext_login_invite_code)
    LocalEditText idEdittextLoginInviteCode;
    @BindView(R.id.ll_phone_number)
    LinearLayout mLlPhone;
    @BindView(R.id.cb_aggreed)
    CheckBox mCbAgreed;


    String phoneStr;

    String sid;
    String smsCode;
    String captcha;

    LoginRequestBean loginRequestBean;

    @Override
    protected void initBeforeSetContentView() {
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

//    TimeTest test = new TimeTest();



    @Override
    protected void init() {

        //      refreshCaptcha();
        RxBus.get().register(this);
        editTextPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editTextPhone.setCursorVisible(true);
                    mLlPhone.setActivated(true);
                    InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    manager.showSoftInput(editTextPhone, InputMethodManager.SHOW_IMPLICIT);
                } else {
                    mLlPhone.setActivated(false);
                    editTextPhone.setCursorVisible(false);
                }
            }
        });
        mLlPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editTextPhone.requestFocus();
            }
        });
        loginRequestBean = new LoginRequestBean();
        initLegal();

//        test.check("init");
        mCbAgreed.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mCbAgreed.setSelected(isChecked);
            }
        });
    }

    @Subscribe
    public void errorSmsCode(EventCollection.ErrorSMSCodeEvent event) {
        XLeoToast.showMessage(R.string.sms_code_error);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        test.check("onStart");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions != null && permissions.length > 0) {
            for (int i = 0; i < permissions.length; i++) {
                // if (TextUtils.equals(permissions[i], Manifest.permission.READ_SMS)) {
                //     if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                //         //addSmsObserver();
                //     }
                // }
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
//        test.stop();
    }

    @Override
    protected LoginActPresenter initPresenterImpl() {
        return new LoginactPreImpl();
    }

    private void initLegal() {
        String text = getString(R.string.login_statement);
        final String legal = getString(R.string.login_statement_title);
        SpannableStringBuilder result = new SpanBuilder().init(text)
                .setLinkSpan(text.indexOf(legal) - 1, text.indexOf(legal) + legal.length() + 1, getResources().getColor(R.color.span_link_words),
                        new Function0<Unit>() {
                            @Override
                            public Unit invoke() {
                                DialogManager.showHtmlDialog(LoginActivity.this, BuildConfig.AGREEMENT_URL, legal, true);
                                return null;
                            }
                        }
                ).result();
        mStatementNotify.setMovementMethod(LinkMovementMethod.getInstance());
        mStatementNotify.setText(result);
    }

    /**
     * RefreshCaptcha
     */
    public void refreshCaptcha() {
        sid = RandomStringUtils.randomAlphanumeric(5);

        Glide.with(this)
                .load(CaptchaApi.formatCaptchaUrl("" + sid))
                .signature(new StringSignature("" + System.currentTimeMillis()))
                .into(imageViewCode);
        XLog.INSTANCE.d("sid:  " + sid, 10);
        //        imageViewCode.setImageURI(Uri.parse(CaptchaApi.formatCaptchaUrl(""+sid)));
    }

    @Override
    public void showGraphicCheck() {
        linearLayoutGraphical.setVisibility(View.VISIBLE);
        refreshCaptcha();
    }

    @Override
    public void onCounterFinish() {
        buttonObtain.setText(getResources().getText(R.string.button_obtain_code));
        buttonObtain.setSelected(false);
        buttonObtain.setClickable(true);
    }

    @Override
    public void onCounterTick(long millisUntilFinished) {
        buttonObtain.setSelected(true);
        buttonObtain.setClickable(false);
        buttonObtain.setText(millisUntilFinished / 1000 + "s");
    }

    @Override
    public void onObtainSmsError(String s) {
        new AlertDialog.Builder(LoginActivity.this)
                .setTitle(R.string.tips_title)
                .setMessage(s)
                .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    @Override
    public void onLoginSuccess() {


        try {
            Map<String, Object> options = new HashMap<>();
            options.put(FMAgent.OPTION_DOMAIN, "https://idfptest.tongdun.net");
            options.put(FMAgent.OPTION_BLACKBOX_MAXSIZE, 5 * 1024);
            FMAgent.initWithCallback(LoginActivity.this, FMAgent.ENV_PRODUCTION, options, blackbox -> {
                // 注意这里不是主线程 请不要在这个函数里进行ui操作，否则可能会出现崩溃
                mPresenter.addUserInfo(TokenManager.getInstance().getMobile(),blackbox);
            });
        } catch (FMException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAddUserInfoSuccess() {

        //Log.i("myPhoneNumber:",TokenManager.getInstance().getMobile());
        XLog.INSTANCE.d("myPhoneNumber: " + TokenManager.getInstance().getMobile(), 5);

        setResult(RESULT_OK);
        finish();
    }


    /**
     * Obtain SMS CODE
     */
    @OnClick(R.id.id_button_obtain_code)
    public void getSMSCode() {
        if (editTextPhone.checkLegal()) {
            mPresenter.obtainSmsCode(editTextPhone.getText().toString());
        } else {
            XLeoToast.showMessage(R.string.show_phone_number_illegal);
        }
    }

    /**
     * Obtain Captcha
     */
    @OnClick(R.id.id_imagebutton_refresh)
    public void getCaptcha() {
        refreshCaptcha();
    }

    /**
     * Login
     */
    @OnClick(R.id.id_button_login)
    public void login() {

        if (!editTextPhone.checkLegal()) {
            XLeoToast.showMessage(R.string.show_phone_number_illegal);
        } else if (!editTextSMSCode.checkLegal()) {
            XLeoToast.showMessage(R.string.sms_code_error);
        } else if (!((linearLayoutGraphical.getVisibility() != View.VISIBLE) || editTextGraphicalCode.checkLegal())) {
            XLeoToast.showMessage(R.string.show_graphical_code_error);
        } else if (!mCbAgreed.isChecked()) {
            XLeoToast.showMessage(R.string.show_read_agreement);
        } else {


            FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.BTN_LOGIN, null);

            smsCode = editTextSMSCode.getText().toString().trim();
            captcha = editTextGraphicalCode.getText().toString().trim();
            phoneStr = editTextPhone.getText().toString().trim();
            loginRequestBean.smsCode = new LoginRequestBean.SMSCode("" + smsCode);
            loginRequestBean.mobile = new LoginRequestBean.Mobile("" + phoneStr);
            loginRequestBean.captchaSid = new LoginRequestBean.CaptchaSID("" + sid);
            loginRequestBean.captcha = new LoginRequestBean.Captcha("" + captcha);
            loginRequestBean.inviteCode = idEdittextLoginInviteCode.getText() == null ? "" : idEdittextLoginInviteCode.getText().toString().trim();
            mPresenter.doLogin(loginRequestBean);
        }
//        /**
//         * 自动登录
//         */
//        LoginRequestBean loginRequestBean = new LoginRequestBean();
//        loginRequestBean.smsCode = new LoginRequestBean.SMSCode("000000");
//        loginRequestBean.mobile = new LoginRequestBean.Mobile("060181018211");
//        loginRequestBean.captchaSid = new LoginRequestBean.CaptchaSID("");
//        loginRequestBean.captcha = new LoginRequestBean.Captcha("");
//        loginRequestBean.inviteCode = "";
//        mPresenter.doLogin(loginRequestBean);



    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        RxBus.get().post(new EventCollection.GiveUpLogin());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }
}
